package com.ufenlei.alarm
{
	import flash.events.EventDispatcher;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
	
	import mx.collections.ArrayCollection;
	
	public class AlarmManager extends EventDispatcher
	{
		private var timer:Timer;
		[Bindable]
		public var  list:ArrayCollection;
		[Bindable]
		public var	overdueList:ArrayCollection;
		public var	dealedList:ArrayCollection;
		public function AlarmManager()
		{
			list = new ArrayCollection();
			dealedList = new ArrayCollection();
			overdueList = new ArrayCollection();
			/* var d:Date = new Date();
			addAlarm( new Alarm(new Date(d.time + 30000),"30秒提醒") );
			addAlarm( new Alarm(new Date(d.time + 10000),"10秒提醒") );
			addAlarm( new Alarm(new Date(d.time + 11000),"15秒提醒") );
			addAlarm( new Alarm(new Date(d.time + 1000*60*60),"1hore提醒") );
			addAlarm( new Alarm(new Date(d.time + 1000*60*60*2),"2hour提醒") ); */
		}
		/**
		 * 添加闹钟
		 * 添加一个提醒，并按时间顺序插入到list中 
		 **/
		public function addAlarm(a:Alarm):void{
			for(var i:uint = 0; i <= list.length; i++){
				if(i==list.length ||a.dueTime.time < (list[i] as Alarm).dueTime.time){
					list.addItemAt(a,i);
					break;
				}
			}
			if(list[0] == a){
				setTimer();
			}
		}
		public function setTimer():void{
			if(timer != null){
				timer.stop();
			}
			var d:Date = new Date();
			if(list.length>0){
				var t:Number = (list[0] as Alarm).dueTime.time - d.time; //到提醒时间的毫秒数
				if(t > 0){
					if(timer != null){
						timer.delay = t;
					}else{
						timer = new Timer(t);
						timer.addEventListener(TimerEvent.TIMER,onTimer);			
					}
					timer.start();
				}
			}
		}
		private function onTimer(evt:TimerEvent):void{
			var a:Alarm = list[0] as Alarm;
			this.overdueList.addItem(a);
			this.removeAlarmByIndex(0);
			this.dispatchEvent(new AlarmEvent(AlarmEvent.ALARM_TIME_UP,a));
		}
		public function removeAlarm(a:Alarm):void{
			var i:int = list.getItemIndex(a);
			list.removeItemAt(i);
			if(i==0){
				setTimer();
			}
		}
		public function removeAlarmByIndex(i:uint):void{
			list.removeItemAt(i);
			if(i == 0){
				setTimer();
			}
		}
	}
}